import socket
import time
import struct
from PIL import Image
from io import BytesIO

VER = '1.0'

class RDT10Server:
    def __init__(self, addr : tuple[str, int]) -> None:
        self.serverSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.serverSocket.bind(addr)
        self.data = bytearray()
        self.tmpdata = None
        pass

    # def makepkt(self, rawdata: bytes) -> bytes:
    #     # rdt 1.0 报文格式: 无报文头
    #     return struct.pack("!%ds" % self.pktsize, rawdata)
    
    # def sendpkt(self, pkt: bytes):
    #     self.serverSocket.sendto(pkt, self.target)

    def recvpkt(self) -> bytes:
        return self.serverSocket.recvfrom(1024)[0]

    def extract(self, pkt: bytes) -> bytes:
        # print('len is ', len(pkt))
        rawdata = struct.unpack("!%ds"%len(pkt), pkt)[0]
        return rawdata

    def run(self):
        while True:
            print('at ', len(self.data))
            self.tmpdata = self.extract(self.recvpkt())
            if self.tmpdata == b'':
                print('data fully received.')
                break
            self.data += self.tmpdata
        pass

    pass

s = RDT10Server(('127.0.0.1', 65432))
s.run()

Image.open(BytesIO(s.data)).show()

open(VER + '-server.png', 'wb').write(s.data)
input("Press any key to exit...")
